<template>
  <div class="spec-template-container">
    <el-card class="template-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">规格模板</span>
            <el-button type="primary" @click="handleAddTemplate">新建规格模板</el-button>
          </div>
          <div class="header-right">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索模板名称"
              clearable
              style="width: 200px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="templateList"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column label="规格列表" min-width="300">
          <template #default="{ row }">
            <div class="spec-list">
              <el-tag
                v-for="spec in row.specs"
                :key="spec.name"
                class="spec-tag"
                :type="getSpecTagType(spec.name)"
              >
                {{ spec.name }}: {{ spec.values.join(', ') }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格组合数" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ getSpecCombinationCount(row.specs) }}种</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsCount" label="使用商品数" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                @click="handleEditTemplate(row)"
              >
                编辑
              </el-button>
              <el-button
                type="primary"
                link
                @click="handlePreviewTemplate(row)"
              >
                预览
              </el-button>
              <el-button
                type="danger"
                link
                :disabled="row.goodsCount > 0"
                @click="handleDeleteTemplate(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 规格模板表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建规格模板' : '编辑规格模板'"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="规格列表" prop="specs">
          <div class="spec-list-editor">
            <div v-for="(spec, index) in formData.specs" :key="index" class="spec-item">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item
                    :label="'规格' + (index + 1)"
                    :prop="'specs.' + index + '.name'"
                    :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }"
                  >
                    <el-input v-model="spec.name" placeholder="规格名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="规格值"
                    :prop="'specs.' + index + '.values'"
                    :rules="{ required: true, message: '请输入规格值', trigger: 'blur' }"
                  >
                    <el-select
                      v-model="spec.values"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="请选择或输入规格值"
                    >
                      <el-option
                        v-for="value in spec.valueOptions"
                        :key="value"
                        :label="value"
                        :value="value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" link @click="removeSpec(index)">
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" link @click="addSpec">添加规格</el-button>
          </div>
        </el-form-item>
        <el-form-item label="规格预览">
          <div class="spec-preview">
            <el-table :data="specCombinations" border style="width: 100%">
              <el-table-column
                v-for="spec in formData.specs"
                :key="spec.name"
                :label="spec.name"
                :prop="spec.name"
              />
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTemplate" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 规格预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="规格组合预览"
      width="800px"
    >
      <el-table :data="previewCombinations" border style="width: 100%">
        <el-table-column
          v-for="spec in previewSpecs"
          :key="spec.name"
          :label="spec.name"
          :prop="spec.name"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  getSpecTemplates,
  createSpecTemplate,
  updateSpecTemplate,
  deleteSpecTemplate
} from '@/api/goods'

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 模板列表
const templateList = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = reactive({
  name: '',
  specs: []
})

// 预览对话框
const previewDialogVisible = ref(false)
const previewSpecs = ref([])
const previewCombinations = ref([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  specs: [
    { required: true, message: '请添加规格', trigger: 'change' },
    { type: 'array', min: 1, message: '至少添加一个规格', trigger: 'change' }
  ]
}

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true
  try {
    const { data } = await getSpecTemplates({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    templateList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取规格模板列表失败:', error)
    ElMessage.error('获取规格模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchTemplates()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTemplates()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTemplates()
}

// 新增模板
const handleAddTemplate = () => {
  dialogType.value = 'add'
  formData.name = ''
  formData.specs = []
  dialogVisible.value = true
}

// 编辑模板
const handleEditTemplate = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除模板
const handleDeleteTemplate = (row) => {
  ElMessageBox.confirm(
    '确定要删除该规格模板吗？删除后不可恢复',
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }
  ).then(async () => {
    try {
      await deleteSpecTemplate(row.id)
      ElMessage.success('删除成功')
      fetchTemplates()
    } catch (error) {
      console.error('删除规格模板失败:', error)
      ElMessage.error('删除规格模板失败')
    }
  }).catch(() => {})
}

// 预览模板
const handlePreviewTemplate = (row) => {
  previewSpecs.value = row.specs
  previewCombinations.value = generateSpecCombinations(row.specs)
  previewDialogVisible.value = true
}

// 保存模板
const handleSaveTemplate = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    if (dialogType.value === 'add') {
      await createSpecTemplate(formData)
      ElMessage.success('创建成功')
    } else {
      await updateSpecTemplate(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存规格模板失败:', error)
      ElMessage.error('保存规格模板失败')
    }
  } finally {
    saving.value = false
  }
}

// 规格相关
const addSpec = () => {
  formData.specs.push({
    name: '',
    values: [],
    valueOptions: []
  })
}

const removeSpec = (index) => {
  formData.specs.splice(index, 1)
}

// 规格组合
const specCombinations = computed(() => {
  return generateSpecCombinations(formData.specs)
})

// 生成规格组合
const generateSpecCombinations = (specs) => {
  if (!specs.length) return []
  
  const combinations = []
  const generateCombinations = (specs, current = {}, index = 0) => {
    if (index === specs.length) {
      combinations.push({ ...current })
      return
    }
    
    const spec = specs[index]
    spec.values.forEach(value => {
      generateCombinations(specs, { ...current, [spec.name]: value }, index + 1)
    })
  }
  
  generateCombinations(specs)
  return combinations
}

// 获取规格组合数量
const getSpecCombinationCount = (specs) => {
  return specs.reduce((count, spec) => count * spec.values.length, 1)
}

// 获取规格标签类型
const getSpecTagType = (name) => {
  const types = ['', 'success', 'warning', 'danger', 'info']
  const index = name.split('').reduce((sum, char) => sum + char.charCodeAt(0), 0)
  return types[index % types.length]
}

// 初始化
onMounted(() => {
  fetchTemplates()
})
</script>

<style scoped>
.spec-template-container {
  padding: 20px;
}

.template-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.spec-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.spec-tag {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.spec-list-editor {
  .spec-item {
    margin-bottom: 16px;
    padding: 16px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.spec-preview {
  margin-top: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局优化 */
@media screen and (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-left,
  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .spec-list-editor {
    .el-col {
      width: 100%;
    }
  }
}
</style> 